#include "stm32f10x.h"
#include "wdtx_led.h"

struct ledStruct
{
	GPIO_TypeDef* GPIOx;
	uint16_t GPIO_Pin;
};

List LED_NewInstance(uint16_t maxLength)
{
	return List_newInstance(sizeof(struct ledStruct),maxLength);
}

void LED_destroy(List list)
{
	List_destroy(list);
}

void LED_add(List group,GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin)
{
	GPIO_InitTypeDef GPIO_InitStructure;
	struct ledStruct led;
	
	RCC_APB2ENR_GPIO_Init(GPIOx);
	
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_Init(GPIOx,&GPIO_InitStructure);
	
	GPIOx->BSRR |= GPIO_Pin;
	
	led.GPIOx = GPIOx;
	led.GPIO_Pin = GPIO_Pin;
	List_add(group,&led);
}

void LED_addCustom(List group,GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin)
{
	struct ledStruct led;
	
	RCC_APB2ENR_GPIO_Init(GPIOx);
	
	GPIOx->BSRR |= GPIO_Pin;
	
	led.GPIOx = GPIOx;
	led.GPIO_Pin = GPIO_Pin;
	List_add(group,&led);
}

void LED_on(List group, u8 i)
{
	struct ledStruct *led;
	led = List_get(group,i);
	led->GPIOx->BRR |= led->GPIO_Pin;
}

void LED_off(List group, u8 i)
{
	struct ledStruct *led;
	led = List_get(group,i);
	led->GPIOx->BSRR |= led->GPIO_Pin;
}

void LED_toggle(List group, u8 i)
{
	struct ledStruct *led;
	led = List_get(group,i);
	if(led->GPIOx->ODR & led->GPIO_Pin)
	{
		led->GPIOx->ODR &= ~led->GPIO_Pin;
	}
	else
	{
		led->GPIOx->ODR |= led->GPIO_Pin;
	}
}

void LED_onAndOff(List group,u32 value)
{
	u8 i;
	u8 length = List_getLength(group);
	for(i = 0; i < length; i++)
	{
		if((value & 1 << i) != 0)
		{
			LED_on(group,i);
		}
		else
		{
			LED_off(group,i);
		}
	}
}

